package com.gaojiabao.panghu.service.impl;

import com.alibaba.fastjson2.util.DateUtils;
import com.gaojiabao.panghu.data.property.MinioProperties;
import com.gaojiabao.panghu.service.UploadService;
import com.gaojiabao.panghu.utils.Result;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * @Author: gaojiabao
 * @Date: 2024/11/5 19:40
 */
@Service
public class UploadServiceImpl implements UploadService {
    @Resource
    private MinioProperties minioProperties;

    //文件上传
    @Override
    public Result<?> upload(MultipartFile multipartFile) {
        try {
            // 创建一个Minio的客户端对象
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(minioProperties.getEndpointUrl())
                    .credentials(minioProperties.getAccessKey(), minioProperties.getSecureKey()).build();

            // 判断桶是否存在
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
            if (!found) {       // 如果不存在，那么，此时就创建一个新的桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            } else {  // 如果存在打印信息
                System.out.println("Bucket 'panghu' already exists.");
            }

            // 设置存储对象名称 dateDir-文件夹名称  uuid-文件名称
            String dateDir = DateUtils.format(new Date(), "yyyyMMdd");
            String uuid = UUID.randomUUID().toString().replace("-", "");
            //20230801/443e1e772bef482c95be28704bec58a901.jpg
            String fileName = dateDir + "/" + uuid + "_" + multipartFile.getOriginalFilename();
            System.out.println(fileName);

            PutObjectArgs putObjectArgs = PutObjectArgs
                    .builder()
                    .bucket(minioProperties.getBucketName())
                    .stream(multipartFile.getInputStream(), multipartFile.getSize(), -1)
                    .object(fileName).build();
            minioClient.putObject(putObjectArgs);

            //资源访问路径
            String accessPath = minioProperties.getEndpointUrl() + "/" + minioProperties.getBucketName() + "/" + fileName;
            return Result.ok(Map.of("accessPath",accessPath));

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
